<?php 
/****

	If you want the best of the world,
give the world your best anytime！
            				——不二
                							
****/

defined('ACCESS')||exit('Forbidden!');

//mysql类，单例模式
class Mysql {
	private $host;
	private $user;
	private $password;
	private $dbname;
	private $charset;
	private $mysqli;
	private static $db;

	private function __construct(){
		$this->host = isset($GLOBALS['config']['mysql']['host'])?$GLOBALS['config']['mysql']['host']:'localhost';
		$this->user = isset($GLOBALS['config']['mysql']['user'])?$GLOBALS['config']['mysql']['user']:'root';
		$this->password = isset($GLOBALS['config']['mysql']['password'])?$GLOBALS['config']['mysql']['password']:'';
		$this->dbname = isset($GLOBALS['config']['mysql']['dbname'])?$GLOBALS['config']['mysql']['dbname']:'';
		$this->charset = isset($GLOBALS['config']['mysql']['charset'])?$GLOBALS['config']['mysql']['charset']:'utf8';

		//连接数据库
		$this->mysqli = mysqli_init();
		$this->conn();

		//设置字符集
		$this->mysqli->query("set names ".$this->charset);

	}

	private function conn(){
		if(!$this->mysqli->real_connect($this->host,$this->user,$this->password,$this->dbname)){
			echo '数据库连接失败!<br>';
			echo '错误代号：'.$this->mysqli->connect_errno().'<br>';
			echo '错误信息：'.$this->mysqli->connect_error().'<br>';
			die();
		}

	}

	//开放一个对外开口
	public static function getInstance(){
		if(self::$db == null){
			self::$db = new self;
		}
		return self::$db;
	}

	//执行一个查询
	public function query($sql){
		if($res = $this->mysqli->query($sql)){
			return $res;
		}else {
			echo '查询失败!<br>';
			echo '错误信息：'.$this->mysqli->error.'<br>';
			die();
		}
	}

	//查询多行
	public function getAll($sql){
		$res = $this->query($sql);
		$data = array();
		while ($row = $res->fetch_assoc()) {
			$data[] = $row;
		}
		return $data;
	}

	//查询一行
	public function getRow($sql){
		$res = $this->query($sql);
		return $res->fetch_assoc();
	}

	//查询单个数据
	public function getOne($sql){
		$res = $this->query($sql);
		return $res->fetch_row()[0];
	}
}
